from rest_framework.permissions import IsAuthenticated
from utils.json_response import ErrorResponse, SuccessResponse
from utils.viewset import CustomModelViewSet
from system.home.models import Navigation
from system.home.serializers import NavSerializer, NavCreateUpdateSerializer


class NavViewSet(CustomModelViewSet):
    queryset = Navigation.objects.all()
    serializer_class = NavSerializer
    create_serializer_class = NavCreateUpdateSerializer
    update_serializer_class = NavCreateUpdateSerializer
    permission_classes = [IsAuthenticated]

    def partial_update(self, request, *args, **kwargs):
        navigation = Navigation.objects.filter(id=kwargs.get('pk')).first()
        sort = request.data.get('sort')
        if not navigation:
            return ErrorResponse(message='未找到指定记录')
        if sort:
            if sort == 'up':
                tmp = Navigation.objects.filter(sort_id__gt=navigation.sort_id).last()
            else:
                tmp = Navigation.objects.filter(sort_id__lt=navigation.sort_id).first()
            if tmp:
                print(tmp.id)
                tmp.sort_id, navigation.sort_id = navigation.sort_id, tmp.sort_id
                tmp.save()
        navigation.save()
        return SuccessResponse(data='', message="更新成功")
